package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.SubcategoryDTO;
import com.lastproject.ejb.entities.Subcategory;
import com.lastproject.ejb.util.SubcategoryConversion;

/**
 * Session Bean implementation class SubcategoryDAO author : Zier Erik
 */
@Stateless
public class SubcategoryDAO implements SubcategoryDAORemote {

	@PersistenceContext
	private EntityManager em;
	@EJB
	SubcategoryConversion conv;

	public SubcategoryDAO() {
	}

	@Override
	public void create(SubcategoryDTO entity) {
		em.persist(conv.fromDTO(entity));
	}

	@Override
	public void edit(SubcategoryDTO entity) {
		em.merge(conv.fromDTO(entity));
	}

	@Override
	public void remove(SubcategoryDTO entity) {
		Subcategory subcategory = em.find(Subcategory.class,
				conv.fromDTO(entity).getId());
		em.remove(subcategory);
	}

	@Override
	public SubcategoryDTO findById(Object id) {
		Subcategory subcategory = em.find(Subcategory.class, id);
		return conv.fromEntity(subcategory);
	}

	@Override
	public List<SubcategoryDTO> findAll() {

		List<Subcategory> subcategorys = em.createNamedQuery(
				"Subcategory.findAll", Subcategory.class).getResultList();

		List<SubcategoryDTO> subcategorydtolist = new ArrayList<SubcategoryDTO>();

		for (Subcategory subcategory : subcategorys) {

			SubcategoryDTO sDto = new SubcategoryDTO();
			sDto = conv.fromEntity(subcategory);
			subcategorydtolist.add(sDto);
		}

		return subcategorydtolist;
	}

	@Override
	public SubcategoryDTO findByName(String subcategory) {
		// TODO Auto-generated method stub
		return conv.fromEntity(em
				.createNamedQuery("Subcategory.findByName", Subcategory.class)
				.setParameter("nameParam", subcategory).getResultList().get(0));
	}

}
